import React, {Component} from 'react';
import {connect} from 'react-redux';
import {NavBar, List, InputItem, Grid, Icon} from 'antd-mobile';

import {sendMsg, readMsg} from '../../redux/actions';

const Item = List.Item;

class Chat extends Component {
    //在第一次render()之前回调
    componentWillMount() {
        this.emojis = ['😀', '😁', '😂', '🤣', '😃', '😄', '❤', '😅', '😉', '', '', '', '', '',
            '', '', '', '', '', '', '❤', '', '', '', '', '', '', '',
            '', '', '', '', '', '', '❤', '', '', '', '', '', '', ''];
        this.emojis = this.emojis.map(value => ({text: value}));
    }

    componentDidMount() {
        //初始显示列表
        window.scrollTo(0, document.body.scrollHeight);
    }

    componentDidUpdate() {
        // 更新显示列表
        window.scrollTo(0, document.body.scrollHeight);
    }

    componentWillUnmount() {
        //发请求更新消息的未读状态
        const from = this.props.match.params.userid;    //目标
        const to = this.props.user._id;       //我的
        this.props.readMsg(from, to);
    }

    state = {
        content: '',
        isShow: false //是否显示表情列表
    }

    handleSend = () => {
        const from = this.props.user._id;//谁发
        const to = this.props.match.params.userid; //发给谁（获取到路由上面的参数）
        const content = this.state.content.trim(); //发送的信息
        //发送请求(发消息)
        if (content) {
            this.props.sendMsg({from, to, content});
        }
        //清除数据
        this.setState({content: '', isShow: false});
        //滑动到底部
        window.scrollTo(0, document.body.scrollHeight);
    }

    //切换表情列表的显示
    toggleShow = () => {
        const isShow = !this.state.isShow;
        this.setState({isShow});
        if (isShow) {
            // 异步手动派发 resize 事件,解决表情列表显示的 bug
            setTimeout(() => {
                window.dispatchEvent(new Event('resize'))
            }, 0);
        }
    }

    render() {
        const {user} = this.props;
        const {users, chatMsgs} = this.props.chat;

        //计算当前聊天的chatId
        const meId = user._id;
        if (!users[meId]) {
            return null;
        }
        const targetId = this.props.match.params.userid;
        const chatId = [meId, targetId].sort().join('_');

        //对chatMsgs进行过滤
        const msgs = chatMsgs.filter(msg => msg.chat_id === chatId);

        //得到目标用户的头像
        const targetHeader = users[targetId].header;
        const targetIcon = targetHeader ? require(`../../assets/images/${targetHeader}.png`) : null;

        return (
            <div id='chat-page'>
                <NavBar
                    icon={<Icon type='left'/>}
                    className='stick-header'
                    onLeftClick={() => this.props.history.goBack()}
                >
                    {users[targetId].username}
                </NavBar>
                <List style={{marginBottom: 50, marginTop: 50}}>
                    {
                        msgs.map(msg => {
                            if (meId == msg.to) { //别人发给我的
                                return (
                                    <Item
                                        key={msg._id}
                                        thumb={targetIcon}>
                                        {msg.content}
                                    </Item>
                                )
                            } else {//我自己发的
                                return (
                                    <Item
                                        key={msg._id}
                                        className='chat-me' extra='我'>
                                        {msg.content}
                                    </Item>
                                )
                            }
                        })
                    }
                </List>
                <div className='am-tab-bar'>
                    <InputItem
                        placeholder="请输入"
                        value={this.state.content}
                        onChange={val => this.setState({content: val})}
                        extra={
                            <div>
                                <span onClick={this.toggleShow} style={{marginRight: 10}}>😀</span>
                                <span onClick={this.handleSend}>发送</span>
                            </div>
                        }
                    />
                    {
                        this.state.isShow ? (
                            <Grid
                                data={this.emojis}
                                columnNum={8}
                                carouselMaxRow={4}
                                isCarousel={true}
                                onClick={(item) => {
                                    this.setState({content: this.state.content + item.text})
                                }}
                            />
                        ) : null
                    }

                </div>
            </div>
        )
    }
}

export default connect(
    state => ({user: state.user, chat: state.chat}),
    {sendMsg, readMsg}
)(Chat);